﻿#include <QDebug>
#include <QListView>
#include <com_manager.h>

#include "page_info_3.h"
#include "ui_page_info_3.h"
#include "mhelper.h"


#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif


PageInfo_3::PageInfo_3(QWidget* parent)
	: QWidget(parent)
    , ui(new Ui::PageInfo_3)
{
	ui->setupUi(this);

    receiveCount = 0;
    sendCount = 0;
    isShow = true;
    isAutoClear = false;
    isHexSend = ui->ckHexSend->isChecked();
    isHexReceive = ui->ckHexReceive->isChecked();
    isDebug = false;


	initWnd();

}

PageInfo_3::~PageInfo_3()
{
	delete ui;
}

void PageInfo_3::on_button_send_clicked()
{

}


void PageInfo_3::initWnd()
{

	QStringList comList;//串口号
	QStringList baudList;//波特率
	QStringList parityList;//校验位
	QStringList dataBitsList;//数据位
	QStringList stopBitsList;//停止位

	ui->txtSend->setView(new QListView);

#ifdef Q_OS_MACOS
	ui->txtSend->setStyleSheet("QComboBox{min-height: 30px;min-width: 120px;font-size:18px;"
		"color:rgb(0, 120, 215); border-radius: 3px; padding: 1px 5px 1px 3px;	font: 75 15pt \"Times\";} "
		"QComboBox::drop-down{width: 10px;background-color: rgb(0, 105, 217,150) }"
		"QComboBox QAbstractItemView{background-color: white;color:gray;font-size:15px;}"
		"QComboBox QAbstractItemView:item{min-height: 30px; min-width: 120px; }");
#else
	ui->txtSend->setStyleSheet("QComboBox{min-height: 30px;min-width: 120px;font-size:18px;"
		"color: rgb(0, 120, 215); border-radius: 3px; padding: 1px 5px 1px 3px;	font: 75 15pt \"Times\";} "
		"QComboBox::drop-down{width: 10px;background-color: rgb(0, 105, 217,150) }"
		"QComboBox QAbstractItemView{background-color: white;color:gray;font-size:15px;}"
		"QComboBox QAbstractItemView:item{min-height: 30px; min-width: 120px; }");

#endif
//	enumerator = new QextSerialEnumerator(this);
//	enumerator->setUpNotifications();

//	connect(enumerator, SIGNAL(deviceDiscovered(QextPortInfo)), SLOT(onPortAddedOrRemoved()));
//	connect(enumerator, SIGNAL(deviceRemoved(QextPortInfo)), SLOT(onPortAddedOrRemoved()));

    foreach(QString info, com_manager::instance()->comList )
	{
        if (info.isEmpty() == false)
            comList.append(info);
	}

	ui->cboxPortName->addItems(comList);
	ui->cboxPortName->setCurrentIndex(0);

	baudList << "1200" << "1800" << "2400" << "4800" << "9600"
		<< "19200" << "38400" << "56000" << "57600"
		<< "115200" << "128000" << "921600";

	ui->cboxBaudRate->addItems(baudList);
	ui->cboxBaudRate->setCurrentIndex(9);

	parityList << "无" << "奇" << "偶";

#ifdef Q_OS_WIN//如果是windows系统
	parityList << "标志";
#endif

	parityList << "空格";

	ui->cboxParity->addItems(parityList);
	ui->cboxParity->setCurrentIndex(0);

	dataBitsList << "5" << "6" << "7" << "8";
	ui->cboxDataBit->addItems(dataBitsList);
	ui->cboxDataBit->setCurrentIndex(3);

	stopBitsList << "1";

#ifdef Q_OS_WIN//如果是windows系统
	stopBitsList << "1.5";
#endif

	stopBitsList << "2";

	ui->cboxStopBit->addItems(stopBitsList);
	ui->cboxStopBit->setCurrentIndex(0);

	//读取数据(采用定时器读取数据，不采用事件，方便移植到linux)
	myReadTimer = new QTimer(this);
	myReadTimer->setInterval(300);
	connect(myReadTimer, SIGNAL(timeout()), this, SLOT(ReadMyCom()));

	//发送数据
	mySendTimer = new QTimer(this);
	mySendTimer->setInterval(5000);
	connect(mySendTimer, SIGNAL(timeout()), this, SLOT(WriteMyCom()));

	//保存数据
    // mySaveTimer = new QTimer(this);
    // mySaveTimer->setInterval(5000);
    // connect(mySaveTimer, SIGNAL(timeout()), this, SLOT(SaveMyCom()));

	//显示日期时间
    // myTimer = new QTimer(this);
    // myTimer->start(1000);
    // connect(myTimer, SIGNAL(timeout()), this, SLOT(SetTime()));

	QDate dateNow = QDate::currentDate();
	ui->labDate->setText(QString("日期: %1").arg(dateNow.toString("yyyy年MM月dd日 dddd")));

	for (int i = 1; i <= 60; i++)
	{
		ui->cboxSend->addItem(QString::number(i) + "秒");
		ui->cboxSave->addItem(QString::number(i) + "秒");
	}

	ui->cboxSave->setCurrentIndex(4);
	ui->cboxSend->setCurrentIndex(4);

	ui->cboxSend->setEnabled(false);
	ui->cboxSave->setEnabled(false);

	this->ChangeEnable(false);
	//   this->ReadConfigData();//读取发送数据加载到下拉框
	//   this->ReadSendData();//读取数据转发文件

	ui->gbox3->hide();
	ui->txtSend->installEventFilter(this);//安装监听器监听发送数据框回车响应
}


void PageInfo_3::ChangeEnable(bool b)
{
	ui->cboxBaudRate->setEnabled(!b);
	ui->cboxDataBit->setEnabled(!b);
	ui->cboxParity->setEnabled(!b);
	ui->cboxPortName->setEnabled(!b);
	ui->cboxStopBit->setEnabled(!b);

	ui->gbox2->setEnabled(b);
	ui->gbox3->setEnabled(b);
	ui->gbox5->setEnabled(b);
	//  ui->gbox6->setEnabled(b);
	ui->btnOpen->setEnabled(true);
}

void PageInfo_3::on_btnOpen_clicked()
{
	QString btnText = ui->btnOpen->text();
	QString openText = "打开串口";
	if (btnText == openText)
	{
		QString portName = ui->cboxPortName->currentText();
#if 0
#ifdef Q_OS_WIN//如果是windows系统
		myCom = new QextSerialPort(portName);
#else
		myCom = new QextSerialPort("/dev/" + portName);
#endif
#else
		myCom = new QextSerialPort(portName);
#endif


		qDebug() << "++++++++++++++++++++++++++++++++++++++++++++";
		qDebug() << "Option on device: " << myCom->portName();
		qDebug() << "++++++++++++++++++++++++++++++++++++++++++++";
		if (myCom->open(QIODevice::ReadWrite))
		{
			//清空缓冲区
			myCom->flush();
			//设置波特率
			myCom->setBaudRate((BaudRateType)ui->cboxBaudRate->currentText().toInt());
			//设置数据位
			myCom->setDataBits((DataBitsType)ui->cboxDataBit->currentText().toInt());
			//设置校验位
			myCom->setParity((ParityType)ui->cboxParity->currentIndex());
			//设置停止位
			myCom->setStopBits((StopBitsType)ui->cboxStopBit->currentIndex());
			myCom->setFlowControl(FLOW_OFF);
			myCom->setTimeout(10);

			this->ChangeEnable(true);
			ui->btnOpen->setText("关闭串口");
			ui->labIsOpen->setText("串口状态：打开");
			this->myReadTimer->start();
		}
	}
	else
	{
		myCom->close();
		this->ChangeEnable(false);
		ui->btnOpen->setText("打开串口");
		ui->labIsOpen->setText("串口状态：关闭");
		this->myReadTimer->stop();

		//这样的话保证每次关闭串口后,自动发送和自动保存定时器不会空转
		ui->ckIsAutoSend->setChecked(false);
		ui->ckIsAutoSave->setChecked(false);
	}
}


void PageInfo_3::on_btnSend_clicked()
{

	this->WriteMyCom();
}


void PageInfo_3::ReadMyCom()
{
	//这个判断尤为重要,否则的话直接延时再接收数据,空闲时和会出现高内存占用
	if (myCom->bytesAvailable() <= 0) { return; }

	mHelper::Sleep(100);//延时100毫秒保证接收到的是一条完整的数据,而不是脱节的
	QByteArray buffer = myCom->readAll();

        if (isShow)
	{
                if (isHexReceive)
		{
			QString tempDataHex = mHelper::ByteArrayToHexStr(buffer);
			QString msgTxt = QString("接收:%1(时间:%2)")
				.arg(tempDataHex)
				.arg(QTime::currentTime().toString("HH:mm:ss"));

			ui->txtDataHex->append(msgTxt);

                        if (isDebug)//2013-8-6增加接收数据后转发数据，模拟设备
			{
				foreach(QString tempData, SendDataList)
				{
					QStringList temp = tempData.split(';');
					if (tempDataHex == temp[0])
					{
						//这里没有跳出循环，有可能一条数据会对应多条数据需要转发
						myCom->write(mHelper::HexStrToByteArray(temp[1]));
					}
				}
			}
		}
		else
		{
			QString tempDataNormal = QString(buffer);
			ui->txtDataHex->append(QString("接收:%1时间:%2")
				.arg(tempDataNormal)
				.arg(QTime::currentTime().toString("HH:mm:ss")));

                        if (isDebug)//2013-8-6增加接收数据后转发数据，模拟设备
			{
				foreach(QString tempData, SendDataList)
				{
					QStringList temp = tempData.split(';');
					if (tempDataNormal == temp[0])
					{
						//这里没有跳出循环，有可能一条数据会对应多条数据需要转发
#if (QT_VERSION <= QT_VERSION_CHECK(5,0,0))
						myCom->write(temp[1].toAscii());
#else
						myCom->write(temp[1].toLatin1());
#endif
					}
				}
			}
		}

                receiveCount = receiveCount + buffer.size();
                ui->labReceive->setText(QString("接收:%1 字节").arg(receiveCount));
	}
}

void PageInfo_3::WriteMyCom()
{
	QString str = ui->txtSend->currentText();
	if (str == "") { ui->txtSend->setFocus(); return; }//发送数据为空
	QString attached = " ";
	if (ui->checkBox_attached_chars->isChecked())
	{
		attached = mHelper::HexStrToByteArray(ui->lineEdit_attahced->text());

	}
	if (!myCom->isOpen()) { return; }//串口没有打开

	int size = 0;
	QByteArray outData = "";
        if (!isHexSend)//转化为16进制发送
	{
#if (QT_VERSION <= QT_VERSION_CHECK(5,0,0))
		outData = str.toAscii();
#else
		outData = str.toLatin1();
#endif
		if (ui->checkBox_attached_chars->isChecked())
		{
		}

		size = outData.size();
		//outData = mHelper::HexStrToByteArray(str);
		if (ui->checkBox_attached_chars->isChecked())
		{
			outData.append(attached);

		}

		myCom->write(outData);
	}
	else
	{
		outData = mHelper::HexStrToByteArray(str);
		if (ui->checkBox_attached_chars->isChecked())
		{
			outData.append(attached);

		}

		myCom->write(outData);
	}
	size = outData.size();

	ui->txtDataHex->append(QString("发送:%1 时间:%2")
		.arg(str)
		.arg(QTime::currentTime().toString("HH:mm:ss")));

        sendCount = sendCount + size;
        ui->labSend->setText(QString("发送: %1 字节").arg(sendCount));

        if (isAutoClear)
	{
		ui->txtSend->setCurrentIndex(-1);
		ui->txtSend->setFocus();
	}
	else {
		for (int i = 0; i < ui->txtSend->count(); i++)
		{
			if (ui->txtSend->itemText(i) == str)
				return;
		}
		ui->txtSend->addItem(str);
	}
}

